#include "SeqList.h"

void SListInit(SList* ps)
{
	ps->arr = NULL;
	ps->capacity = 0;
	ps->size = 0;
}


void SListDestroy(SList* ps)
{
	free(ps->arr);
	ps->arr = NULL;
	ps->capacity = 0;
	ps->size = 0;
}


void SListPrint(SList* ps)
{
	for (int i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->arr[i]);
	}
	printf("\n");
}

void SListCheckCapacity(SList* ps)
{
	if (ps->capacity == ps->size)
	{
		int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		SListDataType* tmp = (SListDataType*)realloc(ps->arr, sizeof(SListDataType) * newcapacity);
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}
		ps->arr = tmp;
		ps->capacity = newcapacity;
	}
}

void SListPushFront(SList* ps, SListDataType x)
{
	SListCheckCapacity(ps);
	ps->size++;
	for (int i = ps->size-1; i >=0; i--)
	{
		ps->arr[i+1] = ps->arr[i];
	}
	ps->arr[0] = x;
}

void SListPopFront(SList* ps)
{
	assert(ps->size > 0);
	for (int i = 0; i < ps->size-1; i++)
	{
		ps->arr[i] = ps->arr[i + 1];
	}
	ps->size--;
}
void SListPushBack(SList* ps, SListDataType x)
{
	SListCheckCapacity(ps);
	ps->arr[ps->size++] = x;
}

void SListPopBack(SList* ps)
{
	assert(ps->size > 0);
	ps->size--;
}


void SListInsert(SList* ps, int pos, SListDataType x)
{
	SListCheckCapacity(ps);
	ps->size++;
	for (int i = ps->size-1; i >= pos; i--)
	{
		ps->arr[i + 1] = ps->arr[i];
	}
	ps->arr[pos] = x;

}



void SListErase(SList* ps, int pos)
{
	for (int i = pos; i < ps->size-1; i++)
	{
		ps->arr[i] = ps->arr[i + 1];
	}
	ps->size--;
}


int SListFind(SList* ps, SListDataType x)
{
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->arr[i] == x)
			return i;
	}
	return -1;
}
